<template>
  <div class="FormBoListEditPermissionConf">
    <div v-if="permissionData.length>0" style="margin-top: 10px">
      <a-button type="primary" @click="addPermission">{{formBoListI18n('addPermission','新增权限')}}</a-button>
      <a-button style="margin-left: 10px" type="primary" @click="previewPermission">{{formBoListI18n('previewPermission','预览列表')}}</a-button>
    </div>
    <div class="FormBoListEditPermissionConf-common" v-if="permissionData.length>0">
      <div class="FormBoListEditPermissionConf-common-le">
        <div class="FormBoListEditPermissionConf-common-le-head">{{formBoListI18n('permissionList','权限列表')}}</div>
        <div style="padding: 14px">
          <div :class="[curPermissionId==permission.permissionId?'FormBoListEditPermissionConf-key FormBoListEditPermissionConf-list-le':'FormBoListEditPermissionConf-list-le']" v-for="(permission, index) in permissionData" :key="permission.permissionId" @click="loadPermission(permission,index)" :title="permission.name">{{ permission.name }}</div>
        </div>
      </div>
      <div class="FormBoListEditPermissionConf-common-ri" v-if="loadStatus">
        <div  class="FormBoListEditPermissionConf-common-le-head">
          <div style="flex:1"> <a-tag style="margin-right: 10px" :color="statusMap[curPermission.status].color">{{statusMap[curPermission.status].text}}</a-tag>{{curPermission.name}}</div>
          <div style="display: flex;height: 40px;align-items: center;margin-right: 20px">
            <div class="editPermission"><a-icon type="setting" @click="editPermission" /></div>
            <div class="editPermission"> <a-icon type="delete" @click="removePermission" /></div>
          </div>
        </div>
        <div class="FormBoListEditPermissionConf-ri-common">
          <div class="FormBoListEditPermissionConf-head">
            {{formBoListI18n('userGroup','组织或以下/用户/用户组')}}
            <a-tooltip>
              <template slot="title">
                {{formBoListI18n('userGroupCommon','这些组织或以下/用户/用户组，拥有下边配置好的列表资源')}}
              </template>
              <a-icon type="question-circle-o"/>
            </a-tooltip>
          </div>
          <div class="FormBoListEditPermissionConf-ri-head">
            <div v-if="curPermission.rightJson!='everyone'" style="flex:1">
              <div v-if="JSON.parse(curPermission.rightJson).subGroup" style="margin-bottom: 5px">
                {{formBoListI18n('subGroup','组织或以下')}}<span v-if="!JSON.parse(curPermission.rightJson).subGroup.include">({{formBoListI18n('notInclude','不包含')}})</span><span v-else>({{formBoListI18n('includeIn','包含')}})</span>:{{JSON.parse(curPermission.rightJson).subGroup.names}}
              </div>
              <div v-if="JSON.parse(curPermission.rightJson).user" style="margin-bottom: 5px">
                {{formBoListI18n('user','用户')}}<span v-if="!JSON.parse(curPermission.rightJson).user.include">({{formBoListI18n('notInclude','不包含')}})</span><span v-else>({{formBoListI18n('includeIn','包含')}})</span>:{{JSON.parse(curPermission.rightJson).user.names}}
              </div>
              <div v-if="JSON.parse(curPermission.rightJson).group" style="margin-bottom: 5px">
                {{formBoListI18n('group','用户组')}}<span v-if="!JSON.parse(curPermission.rightJson).group.include">({{formBoListI18n('notInclude','不包含')}})</span><span v-else>({{formBoListI18n('includeIn','包含')}})</span>:{{JSON.parse(curPermission.rightJson).group.names}}
              </div>
            </div>
            <div v-else>
              <div style="margin-bottom: 5px" v-for="row in rightJsonNameList(curPermission.rightJsonName)">
                {{row}}
              </div>
            </div>
          </div>
          <div class="FormBoListEditPermissionConf-head">
            {{formBoListI18n('ListResource','列表资源')}}
            <a-tooltip>
              <template slot="title">
                {{formBoListI18n('ListResources','列表资源包含以下：字段权限（电脑端+移动端）功能按钮权限（电脑端+移动端）数据权限')}}
              </template>
              <a-icon type="question-circle-o"/>
            </a-tooltip>
          </div>
          <div class="FormBoListEditPermissionConf-head">
            <a-tag style="margin-right: 10px" :color="statusMap[curPermission.datasStatus].color">{{statusMap[curPermission.datasStatus].text}}</a-tag>{{formBoListI18n('DataPermissions','数据权限')}}
          </div>
          <div style="padding: 10px 20px;min-height: 100px;border-bottom: solid 1px #eeeeee;">{{showDatas}}</div>
          <div class="authority-list">
            <div class="authority-name-list">
              <div class="FormBoListEditPermissionConf-common-le-head" style="border-right: 1px solid #eeeeee;"><a-tag style="margin-right: 10px" :color="statusMap[curPermission.fieldsStatus].color">{{statusMap[curPermission.fieldsStatus].text}}</a-tag>{{formBoListI18n('fieldPermiss','字段权限')}}</div>
              <div class="authority-list-common">
                <div class="authority-common">
                  <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('PCPermission','PC端权限')}}</div>
                  <div class="FormBoListEditPermissionConf-list-name" style="margin-top: 0px;margin-left: -11px">
                    <a-tree class="FormBoListEditPermissionConf-tree" :treeData="showColumns" />
                  </div>
                </div>
                <div class="authority-common">
                  <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('mobilePermission','mobile权限')}}</div>
                  <div class="FormBoListEditPermissionConf-list-name">
                    <div style="margin-bottom: 2px" v-for="row in showMobileColumnsSplit(showMobileColumns)"> {{row}}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="authority-button-list">
              <div class="FormBoListEditPermissionConf-common-le-head"><a-tag style="margin-right: 10px" :color="statusMap[curPermission.buttonsStatus].color">{{statusMap[curPermission.buttonsStatus].text}}</a-tag>{{formBoListI18n('funcButton','功能按钮')}}</div>
              <div class="authority-list-common">
                <div class="authority-common">
                  <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('PCPermission','PC端权限')}}</div>
                  <div class="FormBoListEditPermissionConf-list-name" style="margin-top: 0px;margin-left: -11px">
                    <a-tree class="FormBoListEditPermissionConf-tree" :treeData="showButtons" />
                  </div>
                </div>
                <div class="authority-common" style="border-right: none">
                  <div class="FormBoListEditPermissionConf-list-head">{{formBoListI18n('mobilePermission','mobile权限')}}</div>
                  <div class="FormBoListEditPermissionConf-list-name">
                    <div style="margin-bottom: 2px" v-for="row in showMobileColumnsSplit(showMobileButtons)"> {{row}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="FormBoListEditPermissionConf-jurisdiction" v-else>
      <img src="@/image/NoJurisdiction.png"/>
      <div style="margin-top: 10px">{{formBoListI18n('permissionGoTo','暂无设置列表权限，去设置吧~')}}</div>
      <div style="margin-top: 10px">{{formBoListI18n('parameter','如果不设置，则列表的字段权限、功能按钮权限和数据权限，能看到列表的所有人都能看到全部，设置后，则以设置的为准')}}</div>
      <a-button style="margin-top: 10px" type="primary" @click="addPermission">{{formBoListI18n('addPermission','新增权限')}}</a-button>
    </div>
    <a-modal
        :title="i18n('list.selectInit','选择列表预览人')"
        style="top: 100px;"
        :width="400"
        v-model="visible"
        :confirmLoading="confirmLoading"
        @ok="handleOk"
    >
      <rx-user-component :single="true" v-model="previewUser" style="width:100%"></rx-user-component>
    </a-modal>
  </div>
</template>

<script>
import FormBoPermissionApi from '@/api/form/core/formBoPermission';
import {Util} from "@lowcode/jpaas-common-lib";
import {mapState} from 'vuex';
import FormBoPermissionEdit from './FormBoPermissionEdit';
import SysAppApi from "@/api/system/core/sysApp";
import {openUrl} from "@/utils/util";
export default {
  name: "FormBoListEditPermissionConf",
  props:["boListId","curAppObj"],
  data(){
    return {
      boListObj:{},
      curPermission:{},
      loadStatus:false,
      curIndex:-1,
      statusMap: {
        'YES': {color: 'green', text: this.formBoListI18n('YES','已启用')},
        'NO': {color: 'red', text: this.formBoListI18n('NO','已禁用')}
      },
      permissionData:[],
      visible: false,
      confirmLoading: false,
      previewUser:[],
      buttons:[],
      columns:[],
      dataConf:[],
      mobileConf:{},
      curPermissionId:[]
    }
  },
  computed:{
    ...mapState({
      user: state => state.appSetting ? state.appSetting.user : {}
    }),
    showColumns(){
      if(!this.curPermission){
        return [];
      }
      let fields=this.curPermission.fields;
      if(!fields){
        return [];
      }
      let ary=fields.split(",");
      return this.parseTree(this.columns,"field","header",function(json){
        return ary.includes(json.key);
      })
    },
    showButtons(){
      if(!this.curPermission){
        return [];
      }
      let buttons=this.curPermission.buttons;
      if(!buttons){
        return [];
      }
      let ary=buttons.split(",");
      return this.parseTree(this.buttons,"btnName","btnLabel",function(json){
        return ary.includes(json.key);
      })
    },
    showDatas(){
      if(!this.curPermission){
        return null;
      }
      let datas=this.curPermission.datas;
      if(!datas){
        return null;
      }
      let ary=datas.split(",");
      return this.dataConf.filter(item=>{
        return ary.includes(item.id);
      }).map(item=>{
        return item.name;
      }).join(",");
    },
    showMobileColumns(){
      if(!this.curPermission){
        return null;
      }
      let mobileFields=this.curPermission.mobileFields;
      if(!this.mobileConf || !this.mobileConf.mobileCols || !mobileFields){
        return null;
      }
      let ary=mobileFields.split(",");
      return this.mobileConf.mobileCols.filter(item=>{
        return ary.includes(item.field);
      }).map(item=>{
        return item.header;
      }).join(",");
    },
    showMobileButtons(){
      if(!this.curPermission){
        return null;
      }
      let mobileButtons=this.curPermission.mobileButtons;
      if(!this.mobileConf || !this.mobileConf.mobileButton || !mobileButtons){
        return null;
      }
      let ary=mobileButtons.split(",");
      return this.mobileConf.mobileButton.filter(item=>{
        return ary.includes(item.btnName);
      }).map(item=>{
        return item.btnLabel;
      }).join(",");
    }
  },
  methods:{
    parseTree(arr,keyField,titleField,callback){
      let tmp=[];
      if(!arr){
        return tmp;
      }
      arr.forEach(item=>{
        let json={title: item[titleField], key: item[keyField]};
        let flag=callback(json);
        let children=this.parseTree(item.children,keyField,titleField,callback);
        if(flag || children.length>0) {
          if(children.length>0){
            json.children=children;
          }
          tmp.push(json);
        }
      })
      return tmp;
    },
    i18n(name,text,key){
      return this.$ti18(name,text,"FormBoPmt",key);
    },
    formBoListI18n(name,text,key){
      return this.$ti18(name,text,"FormBoPmt.FormBoListEditPermissionConf",key);
    },
    loadData(params){
      if(params) {
        this.buttons = params.buttons || [];
        this.columns = params.columns || [];
        this.dataConf = [{id:"all",name:this.formBoListI18n("datasAll","全部数据")},...(params.dataConf || [])];
        this.mobileConf = params.mobileConf || {};
      }
      FormBoPermissionApi.getList(this.boListId).then(res=>{
        if(res.data){
          if(res.data.list.length>0) {
            this.curIndex = 0;
            this.curPermission = res.data.list[this.curIndex];
            this.curPermissionId=[this.curPermission.permissionId];
            this.loadStatus=true;
          }
          this.permissionData=res.data.list;
          this.boListObj=res.data.boListObj;
        }
      })
    },
    previewPermission(){
      this.previewUser=[{id:this.user.userId,name:this.user.fullName}];
      this.visible=true;
    },
    handleOk() {
      if (this.previewUser.length==0 || !this.previewUser[0].id) {
        this.$message.error(this.formBoListI18n('selectInitor','请选择发起人！'))
        return;
      }
      this.visible=false;
      var record = this.boListObj;
      let appId=record.appId;
      SysAppApi.get(appId).then(res=>{
        let app=res.data;
        let path=app.path;
        let url=`${path}/${app.clientCode}/list/${record.key}?appId=${appId}&previewUserId=${this.previewUser[0].id}`;
        let title=record.name;
        openUrl({url:url,title:title,curVm:this,max:true});
      })
    },
    addPermission(){
      this.openPermission();
    },
    editPermission(){
      this.openPermission(this.curPermission.permissionId);
    },
    openPermission(pkId){
      var self=this;
      var conf = {
        component: FormBoPermissionEdit,
        title: (pkId?this.formBoListI18n('editBtn','编辑'):this.formBoListI18n('add','新增'))+this.formBoListI18n('powerConfiguration','权限配置'),
        curVm: this,
        data: {
          pkId:pkId,
          boListObj:self.boListObj,
          columns:self.columns,
          buttons:self.buttons,
          dataConf:self.dataConf,
          mobileCols:self.mobileConf?self.mobileConf.mobileCols || []:[],
          mobileButton:self.mobileConf?self.mobileConf.mobileButton || []:[]
        },
        max:true,
        shade:true
      };
      Util.open(conf, function (action) {
        if (action != 'ok') {
          return;
        }
        if(!pkId){
          self.permissionData.push(this.resultData);
          self.curIndex=self.permissionData.length-1;
        }else {
          for(let i=0;i<self.permissionData.length;i++){
            let obj=self.permissionData[i];
            if(obj.permissionId==pkId){
              self.permissionData[i]=this.resultData;
            }
          }
        }
        self.curPermission = this.resultData;
        self.loadStatus=true;
        self.curPermissionId=[self.curPermission.permissionId];
      });
    },
    removePermission(){
      var self_=this;
      this.$confirm({
        title: self_.$ti18('rxMsa.actionTips','操作提示'),
        zIndex:20000,
        content: self_.i18n('msa.delConfirm','您确定需要删除记录吗？'),
        okText: self_.$ti18('rxForm.ackBtn','确认'),
        cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
        onOk() {
          FormBoPermissionApi.del({ids:self_.curPermission.permissionId}).then(res=>{
            if(res.success) {
              self_.permissionData.splice(self_.curIndex,1);
              if(self_.permissionData[0]){
                self_.loadPermission(self_.permissionData[0]);
                self_.curIndex = 0;
              }
            }
          })
        },
        onCancel() {
        }
      })
    },
    loadPermission(permission,index){
      this.curIndex = index;
      this.curPermissionId=permission.permissionId
      this.curPermission=permission;
      this.loadStatus=true;
    },
    rightJsonNameList(rightJsonName){
      let list = rightJsonName.split(';')
      return list;
    },
    showMobileColumnsSplit(obj){
      if(!obj){
        return [];
      }
      let list = obj.split(',')
      return list;
    }
  }
}
</script>

<style scoped>
.FormBoListEditPermissionConf-tree >>>li{
  padding: 0px!important;
}
.FormBoListEditPermissionConf-tree{
  margin-top: 5px;
}
.authority-list-common{
  display: flex;
  height: calc(100% - 40px);
}
.authority-common{
  flex: 1;
  padding: 17px;
  border-right: 1px solid #eeeeee;
}
.authority-list{
  width: 100%;
  flex: 1;
  display: flex;
}
.authority-name-list{
  flex: 1;
}
.authority-button-list{
  flex: 1;
}
.FormBoListEditPermissionConf{
  display: flex;
  width: 100%;
  height: calc(100% - 27px);
  flex-direction: column;
  border-bottom: 1px solid #eeeeee;
}
.FormBoListEditPermissionConf-common{
  flex: 1;
  margin-top: 10px;
  border-radius: 4px;
  display: flex;
  border: solid 1px #eeeeee;
  overflow: auto;
  border-bottom: none;
}
.FormBoListEditPermissionConf-common-le{
  width: 250px;
  border-right: 1px solid #eeeeee;
  box-sizing: border-box;
}
.FormBoListEditPermissionConf-list-le{
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  padding: 0px 16px;
  margin-bottom: 4px;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;

}
.FormBoListEditPermissionConf-list-le:hover{
  background-color: #f5f7ff;
  color: #1890ff;
}
.FormBoListEditPermissionConf-key{
  background-color: #f5f7ff;
  color: #1890ff;
}
.FormBoListEditPermissionConf-common-ri{
  flex: 1;
  display: flex;
  flex-direction:column;
}
.FormBoListEditPermissionConf-ri-head{
  border-bottom: 1px solid #eeeeee;
  padding: 20px;
  display: flex;
  align-items: center;
}
.editPermission{
  width: 32px;
  height: 32px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: solid 1px #eeeeee;
  text-align: center;
  line-height: 32px;
  margin-left: 20px;
}
.FormBoListEditPermissionConf-list-head{
  border-left: 2px solid #1890ff;
  height: 12px;
  line-height: 12px;
  padding-left: 8px;
}
.FormBoListEditPermissionConf-list-name{
  margin: 10px 0px 20px 10px;
}
.FormBoListEditPermissionConf-jurisdiction{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}
.FormBoListEditPermissionConf-common-le-head{
  height: 40px;
  line-height: 40px;
  border-bottom: solid 1px #eeeeee;
  padding-left: 20px;
  display: flex;
  align-items: center;
  color: #000000;
  font-weight: bold;
}
.FormBoListEditPermissionConf-head{
  height: 40px;
  background-color: #fafafa;
  line-height: 40px;
  padding-left: 20px;
  border-bottom: solid 1px #eeeeee;
  color: #000000;
  font-weight: bold;
}
.FormBoListEditPermissionConf-ri-common{
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
}
</style>